package com.atguigu.oss.service.impl;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.oss.service.OssService;
import com.atguigu.oss.utils.ConstandPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {

    @Override
    public String uploadFileAvatar(MultipartFile file) {

        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = ConstandPropertiesUtils.END_POINT;
        // 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建。
        String accessKeyId = ConstandPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstandPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstandPropertiesUtils.BUCKET_NAME;

        try {
            //oss设置代理
            ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
            conf.setConnectionTimeout(5000);
            conf.setMaxErrorRetry(3);
            conf.setProxyHost("proxy3.bj.petrochina");
            conf.setProxyPort(8080);

            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, conf);

            // 上传文件流。
            InputStream inputStream = file.getInputStream();

            //生成随机数
            String uuid = UUID.randomUUID().toString().replaceAll("-","");

            //创建文件存储再oss的路径，按日期存储
            String filePath = new DateTime().toString("yyyy/MM/dd");

            //获取文件流的文件名
            String filename = file.getOriginalFilename();

            //拼接路径和文件名
            filename = filePath+"/"+uuid+filename;

            //上传oss
            ossClient.putObject(bucketName,filename,inputStream );

            // 关闭OSSClient。
            ossClient.shutdown();

            //手动拼接一个返回路径
            //https://ws-1010.oss-cn-beijing.aliyuncs.com/eva-no1%282%29.jpg
            String url = "https://"+bucketName+"."+endpoint+"/"+filename;

            return url;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
